<template>
  <div class="page">
    <div class="flex justify-between">
      <a-radio-group v-model="questionType" @change="findList()" type="button">
        <a-radio value="SELECT">选择题</a-radio>
        <a-radio value="JUDGE">判断题</a-radio>
      </a-radio-group>
      <a-button @click="addBtn()" type="primary">添加</a-button>
    </div>
    <div class="mt-5 text-left" v-if="defaultKey.length > 0">
      <a-spin class=" w-full" :loading="loading" tip="数据拼命加载中...">
        <a-collapse :default-active-key="defaultKey">
          <a-collapse-item
            v-for="(item, index) in questionList"
            :header="`${index + 1}. ${item.questionTitle}`"
            :key="item.id"
          >
            <template #extra>
              <a-button
                class="mr-5"
                type="primary"
                size="mini"
                @click.stop="update(item)"
                >更新</a-button
              >
              <a-button
                class="mr-5"
                status="danger"
                type="primary"
                size="mini"
                @click.stop="delQues(item.id)"
                >删除</a-button
              >
            </template>
            <div class="">
              <a-row class="grid-demo">
                <a-col :span="12">
                  <div v-if="item.type === 'SELECT'">
                    <div class="mb-2" v-for="key in Object.keys(item.options)">
                      <span class="mr-2"
                        >{{ String.fromCharCode(65 + parseInt(key)) }}：</span
                      >
                      <span>{{ item.options[key] }}</span>
                    </div>
                  </div>
                  <div class="mt-5">
                    <a-button type="primary" status="success"
                      >答案：{{
                        item.type === "SELECT"
                          ? String.fromCharCode(65 + parseInt(item.answerKey))
                          : item.answerKey === "0"
                          ? "错"
                          : "对"
                      }}</a-button
                    >
                  </div>
                </a-col>
                <a-col :span="12">
                  <div>
                    <qrcode-vue
                      :value="qrcodeValue(`${item.id}`)"
                      :size="160"
                      :margin="5"
                      render-as="svg"
                      level="H"
                    />
                  </div>
                </a-col>
              </a-row>
            </div>
          </a-collapse-item>
        </a-collapse>
      </a-spin>
    </div>
    <div v-else>
      <a-empty />
    </div>
    <div>
      <a-modal
        v-model:visible="addModalVisible"
        :title="`录入${typeMap[questionType]}`"
        @cancel="handleCancel"
        @before-ok="handleBeforeOk"
        :footer="false"
      >
        <a-form :model="form" ref="formRef" @submit="handleSubmit">
          <a-form-item
            field="questionTitle"
            label="题目标题"
            :rules="[{ required: true, message: '输入题目标题' }]"
          >
            <a-textarea
              v-model="form.questionTitle"
              placeholder="输入题目标题"
              :auto-size="{
                minRows: 2,
                maxRows: 10,
              }"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            v-if="questionType === 'SELECT'"
            v-for="(option, index) in Object.keys(form.options)"
            :rules="[{ required: true, message: '输入选项内容' }]"
            :field="`options.${index}`"
            :label="`选项${String.fromCharCode(65 + index)}`"
          >
            <a-input
              v-model="form.options[index]"
              :placeholder="`输入选项${String.fromCharCode(65 + index)}内容`"
            />
            <a-button
              v-if="
                index === Object.keys(form.options).length - 1 &&
                Object.keys(form.options).length > 2
              "
              @click="handleDelete(index)"
              :style="{ marginLeft: '10px' }"
              >删除</a-button
            >
          </a-form-item>
          <div class="mb-5" v-if="questionType === 'SELECT'">
            <a-button class="ml-12" @click="handleAdd">添加选项</a-button>
          </div>
          <a-form-item
            field="answerKey"
            v-if="questionType === 'SELECT'"
            label="题目答案"
            :rules="[{ required: true, message: '输入题目正确答案' }]"
          >
            <a-radio-group v-model="form.answerKey">
              <a-radio
                v-for="(key, index) in Object.keys(form.options)"
                :value="key"
                >{{ String.fromCharCode(65 + parseInt(key)) }}</a-radio
              >
            </a-radio-group>
          </a-form-item>
          <a-form-item
            field="answerKey"
            v-if="questionType === 'JUDGE'"
            label="题目答案"
            :rules="[{ required: true, message: '输入题目正确答案' }]"
          >
            <a-radio-group v-model="form.answerKey">
              <a-radio value="1">对</a-radio>
              <a-radio value="0">错</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item>
            <a-button class="-ml-12" html-type="submit" type="primary">
              提交
            </a-button>
            <a-button class="ml-10" @click="$refs.formRef.resetFields()"
              >重置</a-button
            >
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from "vue";
import {
  saveQuestion,
  findByTypeQuestions,
  delQuestion,
} from "@/apis/question";
import QrcodeVue from "qrcode.vue";

const addModalVisible = ref(false);

const typeMap = {
  SELECT: "选择题",
  JUDGE: "判断题",
};

const questionType = ref("SELECT");

const addBtn = () => {
  formRef.value.resetFields();
  form.id = undefined;
  form.options = {
    0: "",
    1: "",
  };
  addModalVisible.value = true;
};

const formRef = ref();
const form = reactive({
  questionTitle: "",
  options: {
    0: "",
    1: "",
  },
  answerKey: "",
  type: questionType.value,
});

const handleAdd = () => {
  form.options[Object.keys(form.options).length] = "";
};
const handleDelete = (index) => {
  delete form.options[index];
};

const handleSubmit = async ({ values, error }) => {
  values.type = questionType.value;
  const res = await saveQuestion(values);
  if (res.success) {
    formRef.value.resetFields();
    findList();
  }
};

const loading = ref(false);
const questionList = ref([]);
const findList = async () => {
  loading.value = true;
  const res = await findByTypeQuestions({ type: questionType.value });
  questionList.value = res.data;
  loading.value = false;
};

const qrcodeValue = (value) => {
  const preix = window.location.origin;
  return `${preix}/answerQues/${value}`;
};

const defaultKey = computed(() => {
  return questionList.value.map((e) => e.id);
});

const delQues = async (id) => {
  const res = await  delQuestion({ id });
  if (res.success) {
    findList();
  }
};

const update = async (data) => {
  Object.assign(form, data);
  addModalVisible.value = true;
};

onMounted(() => {
  findList();
});
</script>

<style lang="scss" scoped></style>
